<template>
  <div class="log-management">
    <el-card>
      <div class="header-actions">
        <h2>操作日志管理</h2>
        <el-button
            type="primary"
            @click="handleExport"
            :loading="exportLoading"
        >
          <el-icon><Download /></el-icon> 导出CSV
        </el-button>
      </div>

      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :model="queryParams" label-width="120px" inline>
          <el-form-item label="用户ID">
            <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable />
          </el-form-item>

          <el-form-item label="操作类型">
            <el-input v-model="queryParams.action" placeholder="请输入操作类型" clearable />
          </el-form-item>

          <el-form-item label="操作对象类型">
            <el-input v-model="queryParams.targetType" placeholder="请输入对象类型" clearable />
          </el-form-item>

          <el-form-item label="操作对象ID">
            <el-input v-model="queryParams.targetId" placeholder="请输入对象ID" clearable />
          </el-form-item>

          <el-form-item label="操作时间">
            <el-date-picker
                v-model="dateRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 统计数据展示 -->
      <div class="statistics-container">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card>
              <div slot="header">按日期统计</div>
              <el-table :data="statistics.dailyStatistics" border>
                <el-table-column prop="date" label="日期" />
                <el-table-column prop="count" label="操作次数" />
              </el-table>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card>
              <div slot="header">按操作类型统计</div>
              <el-table :data="statistics.typeStatistics" border>
                <el-table-column prop="action" label="操作类型" />
                <el-table-column prop="count" label="次数" />
              </el-table>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card>
              <div slot="header">按用户统计</div>
              <el-table :data="statistics.userStatistics" border>
                <el-table-column prop="userId" label="用户ID" />
<!--                <el-table-column prop="userName" label="用户名" />-->
                <el-table-column prop="count" label="操作次数" />
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 日志列表 -->
      <el-table
          :data="logList"
          border
          style="width: 100%; margin-top: 20px;"
          v-loading="loading"
      >
        <el-table-column prop="id" label="日志ID" width="100" />
        <el-table-column prop="userId" label="用户ID" width="100" />
        <el-table-column prop="action" label="操作类型" />
        <el-table-column prop="targetType" label="对象类型" />
        <el-table-column prop="targetId" label="对象ID" width="100" />
        <el-table-column prop="ip" label="操作IP" width="150" />
        <el-table-column prop="createdTime" label="操作时间" width="200" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="handleDetail(scope.row.id)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :total="total"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 日志详情弹窗 -->
    <el-dialog
        v-model="detailVisible"
        title="日志详情"
        width="600px"
    >
      <el-descriptions :column="1" border v-if="currentLog">
        <el-descriptions-item label="日志ID">{{ currentLog.id }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentLog.userId }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">{{ currentLog.action }}</el-descriptions-item>
        <el-descriptions-item label="操作对象类型">{{ currentLog.targetType }}</el-descriptions-item>
        <el-descriptions-item label="操作对象ID">{{ currentLog.targetId }}</el-descriptions-item>
        <el-descriptions-item label="变更详情">{{ currentLog.detail }}</el-descriptions-item>
        <el-descriptions-item label="操作IP">{{ currentLog.ip }}</el-descriptions-item>
        <el-descriptions-item label="操作时间">{{ currentLog.createdTime }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import { LogApi } from '@/api/log'
import http from '@/axios'
// 状态变量
const loading = ref(false)
const exportLoading = ref(false)
const logList = ref([])
const total = ref(0)
const detailVisible = ref(false)
const currentLog = ref(null)
const dateRange = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userId: null,
  action: '',
  targetType: '',
  targetId: null,
  startTime: null,
  endTime: null
})

// 统计数据
const statistics = ref({
  dailyStatistics: [],
  typeStatistics: [],
  userStatistics: []
})

// 监听日期范围变化
watch(dateRange, (newVal) => {
  if (newVal && newVal.length === 2) {
    queryParams.startTime = newVal[0]
    queryParams.endTime = newVal[1]
  } else {
    queryParams.startTime = null
    queryParams.endTime = null
  }
})

// 获取日志列表
const getLogList = async () => {
  try {
    loading.value = true
    const res = await LogApi.getLogList(queryParams)
    logList.value = res.data.records || []
    total.value = res.data.total || 0
  } catch (error) {
    ElMessage.error('获取日志列表失败')
    console.error('获取日志列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const getLogStatistics = async () => {
  try {
    const params = {
      startTime: queryParams.startTime,
      endTime: queryParams.endTime
    }
    const res = await LogApi.getLogStatistics(params)
    statistics.value = res.data || {
      dailyStatistics: [],
      typeStatistics: [],
      userStatistics: []
    }
  } catch (error) {
    ElMessage.error('获取统计数据失败')
    console.error('获取统计数据失败:', error)
  }
}

// 查询按钮点击
const handleQuery = () => {
  queryParams.pageNum = 1
  getLogList()
  getLogStatistics()
}

// 重置查询条件
const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    action: '',
    targetType: '',
    targetId: null,
    startTime: null,
    endTime: null
  })
  dateRange.value = []
  getLogList()
  getLogStatistics()
}

// 分页相关
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getLogList()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getLogList()
}

// 查看详情
const handleDetail = async (id) => {
  try {
    const res = await LogApi.getLogDetail(id)
    currentLog.value = res.data
    detailVisible.value = true
  } catch (error) {
    ElMessage.error('获取日志详情失败')
    console.error('获取日志详情失败:', error)
  }
}

// 导出CSV
const handleExport = async () => {
  try {
    exportLoading.value = true;

    // 构造导出参数（只传递后端支持的参数）
    const params = {};
    if (queryParams.userId) params.userId = queryParams.userId;
    if (queryParams.action) params.action = queryParams.action;
    if (queryParams.startTime) params.startTime = queryParams.startTime;
    if (queryParams.endTime) params.endTime = queryParams.endTime;

    // 使用 LogApi 导出
    await LogApi.exportLogs(params);
    ElMessage.success('导出成功');
  } catch (error) {
    // 安全地处理错误信息
    let msg = '导出失败，请稍后重试';
    if (error && error.message) {
      msg = error.message;
      // 避免显示"未知错误"这样的技术性提示
      if (msg.includes('未知错误') || msg.includes('undefined')) {
        msg = '导出失败，请稍后重试';
      }
    }
    ElMessage.error(msg);
    console.error('导出失败:', error);
  } finally {
    exportLoading.value = false;
  }
};




// 页面挂载时加载数据
onMounted(() => {
  getLogList()
  getLogStatistics()
})
</script>

<style scoped>
.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-container {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.statistics-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>